package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.base.util.JSONResult;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/sessions")
public class SessionsController {

    @Autowired
    private IUserService userService;

    @PostMapping
    public Object login(@RequestParam String email,@RequestParam String password){
        JSONResult jsonResult = new JSONResult();
        try {
            User user = userService.selectEmailAndPassword(email, password);
            jsonResult.setResult(user);
            UserContext.setUserAttribute(user);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.mark(e.getMessage());
        }
        return jsonResult;
    }

    @DeleteMapping
    public Object logout(){
        UserContext.getSession().invalidate();
        return new JSONResult();
    }
}
